package org.jeie.util;
import java.awt.Color;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.util.Stack;

public class FloodFill {
	public static void nonrecursiveFill(BufferedImage img, int i, int j,
			Color newColor) {
		int oldColor = img.getRGB(i, j);
		int newC = newColor.getRGB();
		if (oldColor != newC) {
			Stack<Point> pending = new Stack<Point>();
			pending.push(new Point(i, j));
			while (!pending.empty()) {
				Point p = pending.pop();
				if (isLegal(img, p.x, p.y) && img.getRGB(p.x, p.y) == oldColor) {
					img.setRGB(p.x, p.y, newC);
					pending.push(new Point(p.x - 1, p.y));
					pending.push(new Point(p.x + 1, p.y));
					pending.push(new Point(p.x, p.y - 1));
					pending.push(new Point(p.x, p.y + 1));
				}
			}
		}
	}
	private static boolean isLegal(BufferedImage img, int i, int j) {
		if (i < 0 || j < 0)
			return false;
		if (i >= img.getWidth() || j >= img.getHeight())
			return false;
		return true;
	}
}